import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, removeToken } from '@/utils/auth'
import { constantRoutes } from '@/router/routes'
import { resetRouter } from '@/router'

const whiteList = ['/login']

// 动态加载路由函数
const loadRoleRoutes = async (role) => {
  console.log('当前角色:', role);
  try {
    // 使用动态导入确保模块加载完成
    const routeModule = await import('@/router/routes');
    const { adminRoutes, teacherRoutes } = routeModule;
    
    // 统一角色判断
    const roleMap = {
      admin: adminRoutes,
      teacher: teacherRoutes,
      管理员: adminRoutes,
      讲师: teacherRoutes
    };

    const routes = roleMap[role] || [];
    console.log('实际加载的路由:', routes);
    return routes.map(route => ({
      ...route,
      // 确保每个路由都有path和component
      path: route.path || '',
      component: route.component || Layout,
      children: route.children ? route.children.map(child => ({
        ...child,
        path: child.path || '',
        component: child.component || (() => import('@/views/404'))
      })) : []
    }));
  } catch (error) {
    console.error('路由加载失败:', error);
    return [];
  }
}

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
      return;
    }

    try {
      // 获取用户信息
      if (!store.getters.roles || store.getters.roles.length === 0) {
        await store.dispatch('user/GetInfo').catch(error => {
          console.error('获取用户信息失败:', error);
          throw error;
        });
        console.log('用户权限:', store.getters.buttons)
      }

      // 检查有效角色
      const validRoles = ['admin', 'teacher', '管理员', '讲师'];
      const currentRole = store.getters.role;
      if (!currentRole || !validRoles.includes(currentRole)) {
        throw new Error(`无效的角色: ${currentRole}`);
      }

      // 动态加载路由
      if (!store.getters['permission/addedRoutes']) {
        const accessRoutes = await loadRoleRoutes(currentRole);

        // 重置路由
        try {
          resetRouter();
          // 先添加基础路由
          router.addRoutes(constantRoutes);
          // 添加动态路由
          router.addRoutes([
            ...accessRoutes,
            { path: '*', redirect: '/404', hidden: true }
          ]);
          await store.dispatch('permission/generateRoutes', {
            role: store.getters.role,
            routes: accessRoutes
          });
          store.commit('permission/SET_ADDED_ROUTES', true)
          if (to.path === '/dashboard' && !router.match(to.path).matched.length) {
            return next('/dashboard');
          }
          next({ ...to, replace: true });
        } catch (error) {
          console.error('路由加载失败:', error);
          throw error;
        }
      }
      return next();
    } catch (error) {
      console.error('权限验证失败:', error);
      await store.dispatch('user/resetToken');
      removeToken();
      return next(`/login?redirect=${to.path}`);
    } finally {
      NProgress.done();
    }
  } else {
    whiteList.includes(to.path) ? next() : next(`/login?redirect=${to.path}`);
  }
});

router.afterEach(() => {
  NProgress.done()
})